package com.myphoto.business.photo.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.myphoto.base.annotation.ProductSwagger;
import com.myphoto.base.annotation.SysLog;
import com.myphoto.base.config.properties.IConfig;
import com.myphoto.base.enumtype.LogTypeEnum;
import com.myphoto.base.enumtype.ModuleEnum;
import com.myphoto.base.enumtype.MsgEnum;
import com.myphoto.base.mybatis.photo.entity.PhotoEntity;
import com.myphoto.base.util.R;
import com.myphoto.business.photo.service.PhotoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;

@RestController
@RequestMapping(value = "/photo")
@Api(tags = "相片管理")
public class PhotoController {

    @Autowired
    private PhotoService photoService;
    @Autowired
    private IConfig config;

    /**
    * @description 查询相片列表
    * @author 方安伦
    * @date 2022/04/12 16:57
     **/
    @ApiOperation(value = "查询相片列表", notes = "查询相片列表",httpMethod="POST")
    @ApiOperationSupport( author = "方安伦")
    @RequestMapping("/loadPhotoList")
    @ProductSwagger
    @SysLog(model = ModuleEnum.PHOTO,logType = LogTypeEnum.INFO,value = "查询相片列表",saveToDatabase = true)
    public R<List<PhotoEntity>> loadPhotoList() throws Exception{
        List<PhotoEntity> photoList = photoService.loadPhotoList();
        return R.success(MsgEnum.OPRATE_SUCCESS,photoList);
    }

    /**
     * @description 上传相片
     * @author 方安伦
     * @date 2022/04/12 17:16
     **/
    @ApiOperation(value = "上传相片", notes = "上传相片",httpMethod="POST")
    @ApiOperationSupport( author = "方安伦")
    @RequestMapping("/uploadPhoto")
    @ApiImplicitParams({
            @ApiImplicitParam(name="lastModified",value="相片拍照时间（yyyy-MM-dd HH:mm:ss）",dataType="string", dataTypeClass=java.lang.String.class,paramType = "query",required=true),
            @ApiImplicitParam(name="file",value="相片文件",dataType="__file", dataTypeClass = MultipartFile.class ,paramType = "query",required=true)
    })
    @SysLog(model = ModuleEnum.PHOTO,logType = LogTypeEnum.INFO,value = "上传相片")
    public R uploadPhoto(String lastModified,@RequestPart(name="file") MultipartFile file) throws Exception{
        //1、检查相片文件是否已经存在
        String filename = file.getOriginalFilename();
        boolean flag = photoService.checkFileIsExist(filename);
        if(flag){
            return R.error("该相片文件已经存在！");
        }
        //2.检查相片信息是否已经存在
        boolean infoflag = photoService.checkFileInfoIsExist(filename);
        if(infoflag){
            return R.error("该相片信息已经存在！");
        }
        //3、上传相片
        photoService.uploadPhoto(lastModified,file);
        return R.success(MsgEnum.UPLOAD_SUCCESS);
    }

    /**
    * @description 下载相片
    * @author 方安伦
    * @date 2022/4/14 11:42
    * @param fileName
     **/
    @ApiOperation(value = "下载相片", notes = "下载相片",httpMethod="POST")
    @ApiOperationSupport( author = "方安伦")
    @GetMapping(value="/downloadPhoto/{fileName}")
    @SysLog(model = ModuleEnum.PHOTO,logType = LogTypeEnum.INFO,value = "下载相片")
    public void downloadPhoto(HttpServletResponse response, @PathVariable(value = "fileName",required = true) String fileName) throws Exception{
        boolean flag = photoService.checkFileIsExist(fileName);
        if(flag==false){
            return ;
        }
        //拼接文件存储路径
        String photo_path = config.getConfig().getPhoto_path();//得到上传文件主路径
        String filePath = photo_path + fileName;//得到文件的存储路径
        // 清空response
        response.reset();
        // 设置response的Header
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
        long fileLength = new File(filePath).length();
        response.setHeader("Content-Length", String.valueOf(fileLength));
        response.setContentType("application/octet-stream;charset=UTF-8");
        //获取 response 的输出流，用来输出文件
        ServletOutputStream out = response.getOutputStream();
        //读取，以输入流的形式读取文件
        FileInputStream in = new FileInputStream(filePath);
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer))!=-1) {
            out.write(buffer, 0, len);
        }
        out.flush();
    }

    /**
    * @description 清除冗余图片信息
    * @author 方安伦
    * @date 2022/4/22 9:44
     **/
    @ApiOperation(value = "清除冗余图片信息", notes = "清除冗余图片信息",httpMethod="POST")
    @ApiOperationSupport( author = "方安伦")
    @RequestMapping("/clearErrorPicinfo")
    @ProductSwagger
    @SysLog(model = ModuleEnum.PHOTO,logType = LogTypeEnum.INFO,value = "清除冗余图片信息",saveToDatabase = true)
    public R clearErrorPicinfo() throws Exception{
        photoService.clearErrorPicinfo();
        return R.success(MsgEnum.OPRATE_SUCCESS);
    }
}
